package org.jeecg.modules.pay.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.pay.entity.AccountChange;
import org.jeecg.modules.pay.service.IAccountChangeService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import java.math.BigDecimal;

/**
 * @author OSFung
 * @date 2022-06-15 05:21
 */
@Slf4j
@RabbitListener(queues = "accountChange")
@RabbitComponent(value = "accountChangeListener")
public class AccountChangeListener extends BaseRabbiMqHandler<BaseMap> {

    private ISysUserService sysUserService;

    private IAccountChangeService accountChangeService;

    @Autowired
    public AccountChangeListener(ISysUserService sysUserService, IAccountChangeService accountChangeService) {
        this.sysUserService = sysUserService;
        this.accountChangeService = accountChangeService;
    }

    @RabbitHandler
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                BigDecimal changeNum = map.get("changeNum");
                BigDecimal beforeChange = map.get("beforeChange");
                BigDecimal afterChange = map.get("AfterChange");
                String id = map.get("id");
                SysUser user = sysUserService.getById(id);
                AccountChange accountChange = new AccountChange();
                accountChange.setId(user.getId())
                        .setBeforeChange(beforeChange)
                        .setAfterChange(afterChange)
                        .setChangeNum(changeNum)
                        .setUserName(user.getUsername())
                        .setRealname(user.getRealname());
                accountChangeService.add(accountChange);
            }
        });
    }
}
